
// #region
/**
 * @param:{ view } { 三维地图对象 }
 * @param:{ modulesobj } { gis功能模块 }
 * @param:{ spatialReference } { 坐标系 如果不传 默认为4326 }
 */

// #endregion
export default (view, modulesobj, spatialReference = { wkid: 4326 }) => {
    /**
     * 封装热力图
     * @param:{ freshenLayer() } { Function } @description 刷新layer
     * @param:{ clearCanvas() } { Function } @description 清除效果
     * @param:{ addPoint(data) } { Function } @description 添加数据  data数据格式  [[x, y, degree],[x, y, degree],[x, y, degree]]
     */
    class HeatLayer {
        constructor() {
            let { lang, Point } = modulesobj;
            this.view = view;
            this.lang = lang;
            this.Point = Point;
            //配置热力图的颜色、半径
            this.config = {
                radius: 25,
                gradient: {
                    // "0": "rgba(255, 0, 0, 0)",
                    // "0.3": "rgba(0,0, 255)",
                    // "0.6": "rgb(250, 250, 0)",
                    // "0.85": "rgb(250, 150, 0)",
                    // "0.95": "rgb(255, 50, 0)",


                    0.5: 'rgba(0,0, 255)',
                    0.65: 'rgb(117,211,248)',
                    0.7: 'rgb(0, 255, 0)',
                    0.9: '#ffea00',
                    1.0: 'rgb(255, 50, 0)'
                }
            };
            this.canvas = null;
            this.context = null;
            this.minnum = 1;
            this.maxnum = 1;
            this.visible = true;
            this.spatialReference = spatialReference;
            this.createCanvas();
        }
        /*创建Canvaslayer的容器canvas，添加到map的layers下面*/
        createCanvas() {
            let canvas = document.createElement("canvas");
            canvas.width = this.view.width;
            canvas.height = this.view.height;
            canvas.setAttribute("id", "heatmap");
            canvas.style.position = "absolute";
            canvas.style.top = 0;
            canvas.style.left = 0;
            let parent = document.getElementsByClassName(
                "esri-view-surface"
            )[0];
            parent.appendChild(canvas);
            this.canvas = canvas;
            this.context = document
                .getElementById("heatmap")
                .getContext("2d");
            this.startMapEventListeners();
        }
        /*转换数据*/
        convertHeatmapData(data) {
            var heatPluginData = [];
            for (let i = 0; i < data.length; i++) {
                let screenpoint = this.view.toScreen(
                    new this.Point({
                        // longitude: data[i][0],
                        // latitude: data[i][1],
                        x: data[i][0],
                        y: data[i][1],
                        spatialReference: this.spatialReference
                    })
                );
                // 判断数据是否带有权重，未带有权重属性是默认为1
                if (data[0].length == 3) {
                    heatPluginData.push([
                        Math.round(screenpoint.x),
                        Math.round(screenpoint.y),
                        data[i][2]
                    ]);
                } else {
                    heatPluginData.push([
                        Math.round(screenpoint.x),
                        Math.round(screenpoint.y),
                        1
                    ]);
                }
                if (this.minnum > data[i][2]) {
                    this.minnum = data[i][2];
                }
                if (this.maxnum < data[i][2]) {
                    this.maxnum = data[i][2];
                }
            }
            return {
                points: heatPluginData,
                min: this.minnum,
                max: this.maxnum
            };
        }
        //添加点数据
        addPoint(data) {
            this.data = data;
            let points = this.convertHeatmapData(data);
            //console.log(points)
            points.points.forEach(point => {
                this.context.beginPath();
                let alpha = (point[2] - points.min) / (points.max - points.min);
                this.context.globalAlpha = alpha;
                this.context.arc(
                    point[0],
                    point[1],
                    this.config.radius,
                    0,
                    Math.PI * 2,
                    true
                );
                //绘制一个放射渐变样式的圆
                let gradient = this.context.createRadialGradient(
                    point[0],
                    point[1],
                    0,
                    point[0],
                    point[1],
                    this.config.radius
                );
                gradient.addColorStop(0, "rgba(0,0,0,1)");
                gradient.addColorStop(1, "rgba(0,0,0,0)");
                this.context.fillStyle = gradient;
                this.context.closePath();
                this.context.fill();
            });
            this.MapColors();
            //console.log('haol')
        }
        //设置渐变色带
        getColorPaint() {
            let paletteCanvas = document.createElement("canvas");
            let paletteCtx = paletteCanvas.getContext("2d");
            let gradientConfig = this.config.gradient;
            paletteCanvas.width = 256;
            paletteCanvas.height = 1;
            let gradient = paletteCtx.createLinearGradient(0, 0, 256, 1);
            for (let key in gradientConfig) {
                gradient.addColorStop(key, gradientConfig[key]);
            }
            paletteCtx.fillStyle = gradient;
            paletteCtx.fillRect(0, 0, 256, 1);
            return paletteCtx.getImageData(0, 0, 256, 1).data;
        }
        //映射颜色
        MapColors() {
            let palette = this.getColorPaint();
            let img = this.context.getImageData(
                0,
                0,
                this.canvas.width,
                this.canvas.height
            );
            let imgData = img.data;
            for (let i = 0; i < imgData.length; i++) {
                let alpha = imgData[i];
                let offset = alpha * 4;
                if (!offset) {
                    continue;
                }
                //映射颜色RGB值
                imgData[i - 3] = palette[offset];
                imgData[i - 2] = palette[offset + 1];
                imgData[i - 1] = palette[offset + 2];
            }
            this.context.putImageData(
                img,
                0,
                0,
                0,
                0,
                this.canvas.width,
                this.canvas.height
            );
        }
        /*刷新layer*/
        freshenLayer() {
            this.clearCanvas();
            this.addPoint(this.data);
        }
        /*清除渲染效果*/
        clearCanvas() {
            this.context.clearRect(0, 0, this.view.width, this.view.height);
        }
        removeCanvas() {
            this.clearCanvas()
            document.getElementById("heatmap") && document.getElementById("heatmap").remove();
        }
        /*添加监听*/
        startMapEventListeners() {
            let view = this.view;
            view.watch(
                "extent",
                this.lang.hitch(this, () => {
                    if (!this.visible) return;
                    this.freshenLayer();
                    // console.log('执行了吗11111111');
                })
            );
            view.watch(
                "camera",
                this.lang.hitch(this, () => {
                    if (!this.visible) return;
                    this.freshenLayer();
                    // console.log("执行了吗2222222");
                })
            );
        }
    }

    var heatmap = new HeatLayer();
    return heatmap
}
